package mt.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

import mt.util.base.PathKit;
import mt.util.base.StringKit;

import org.apache.log4j.Logger;


public class PathUtil {
	private static Logger logger = Logger.getLogger(PathUtil.class);
	
	public static String getWSDLFilePathInWebInf(String file){
		if (StringKit.isBlank(file))
			throw new IllegalArgumentException("Parameter of file can not be blank");
		if (file.contains(".."))
			throw new IllegalArgumentException("Parameter of file can not contains \"..\"");
		
		String fullFile;	// String fullFile = PathUtil.getWebRootPath() + file;
		if (file.startsWith(File.separator))
			fullFile = PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator + "WSDL" + file;
		else
			fullFile = PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator +"WSDL" +File.separator + file;
		logger.debug("FilePath:"+fullFile);
		return fullFile;
	}
	
	public static URL getWSDLURLPathInWebInf(String file){
		String fullfile = getWSDLFilePathInWebInf(file);
		 File wsdlFile = new File(fullfile);
         try {
             if (wsdlFile.exists()) {
                 return wsdlFile.toURI().toURL();
             } 
         } catch (MalformedURLException e) {
             e.printStackTrace();
         }
		 throw new NullPointerException("获取不到文件！");
	}
	
	public static String getWebInfPath(){
		PathUtil pathUtil = new PathUtil();
		URL url = pathUtil.getClass().getProtectionDomain().getCodeSource().getLocation();
		String path = url.toString();
		
		int index = path.indexOf("WEB-INF");
	
		if(index != -1){
			path = path.substring(0,index+7);
		}
		
		if(path.startsWith("zip")){
			path = path.substring(4);
		}else if(path.startsWith("file")){
			path = path.substring(6);
		}else if(path.startsWith("jar")){
			path = path.substring(10);
		}
		
		try{
			path = URLDecoder.decode(path,"UTF-8");
		}catch(UnsupportedEncodingException e){
			e.printStackTrace();
		}
		return path;
	}
	
	public static  String getClassPath(){
		PathUtil pathUtil = new PathUtil();
		URL url = pathUtil.getClass().getProtectionDomain().getCodeSource().getLocation();
		String path = url.toString();
		
		int index = path.indexOf("classes");
		if(index != -1){
			path = path.substring(0,index+7);
		}
		
		if(path.startsWith("zip")){
			path = path.substring(4);
		}else if(path.startsWith("file")){
			path = path.substring(6);
		}else if(path.startsWith("jar")){
			path = path.substring(10);
		}
		
		try{
			path = URLDecoder.decode(path,"UTF-8");
		}catch(UnsupportedEncodingException e){
			e.printStackTrace();
		}
		return path;
	}
}
